package com.example.exportPdf;

import cn.hutool.core.date.DateUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PdfGenerator {
//https://www.anyrt.com/blog/list/itextpdf.html
    /**
     * 生成PDF文档
     *
     * @param items   对象集合
     * @param title   文档标题
     * @param headers 表格表头
     * @param fields  对象属性名
     * @return PDF字节数组
     */
    public static <T> void generatePdf(List<Map<String,Object>> items, String title, String[] headers, String[] fields, OutputStream out) throws Exception {
        try {
            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.getInstance(document, out);

            // 添加页眉页脚
            HeaderFooter event = new HeaderFooter(title);
//            HeaderFooter event = new HeaderFooter();
            writer.setPageEvent(event);

            document.open();

            // Windows 下的宋体
            String fontPath = "fonts/simhei.ttf";
            BaseFont bfChinese = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            Font titleFont = new Font(bfChinese, 16, Font.BOLD);
            Font headerFont = new Font(bfChinese, 10, Font.BOLD);
            Font contentFont = new Font(bfChinese, 10, Font.NORMAL);

            // 添加标题
            Paragraph titleParagraph = new Paragraph(title, titleFont);
            titleParagraph.setAlignment(Element.ALIGN_CENTER);
            titleParagraph.setSpacingAfter(20);
            document.add(titleParagraph);

            //  添加生成时间
            Paragraph dateParagraph = new Paragraph("生成时间：" + DateUtil.now(),
                    new Font(bfChinese, 8, Font.ITALIC));
            dateParagraph.setAlignment(Element.ALIGN_RIGHT);
            dateParagraph.setSpacingAfter(10);
            document.add(dateParagraph);

            // 创建表格
            PdfPTable table = new PdfPTable(headers.length);
            table.setWidthPercentage(100);

            // 设置表格样式
            table.setSpacingBefore(10f);
            table.setSpacingAfter(10f);

            PdfPCell pdfCell = new PdfPCell(new Phrase("合并", headerFont));
            pdfCell.setRowspan(1);
            pdfCell.setColspan(3);
            pdfCell.setPadding(5);
            pdfCell.setBorderColor(new BaseColor(200, 200, 200));
            pdfCell.setMinimumHeight(25);
            pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(pdfCell);

            // 设置表头
            BaseColor headerBgColor = new BaseColor(233, 239, 245);
            for (String header : headers) {
                PdfPCell cell = new PdfPCell(new Phrase(header, headerFont));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setBackgroundColor(headerBgColor);
                cell.setPadding(5);
                // 设置表格边框颜色
                cell.setBorderColor(new BaseColor(200, 200, 200));
                cell.setMinimumHeight(25);
                table.addCell(cell);
            }

            // 设置表格内容
            if (!items.isEmpty()) {
                for (Map<String,Object> item : items) {
                    for (String field : fields) {
                        try {
//                            Object value = getFieldValue(item, field);
                            Object value = item.get(field);
                            String cellValue = (value != null) ? value.toString() : "";

                            PdfPCell cell = new PdfPCell(new Phrase(cellValue, contentFont));
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                            cell.setPadding(5);
                            cell.setMinimumHeight(20);

                            // 设置表格边框颜色
                            cell.setBorderColor(new BaseColor(200, 200, 200));

                            table.addCell(cell);
                        } catch (Exception e) {
                            table.addCell(new PdfPCell(new Phrase("", contentFont)));
                        }
                    }
                }
            }

            document.add(table);

            // 添加说明文字
            Paragraph noteParagraph = new Paragraph("注：本文档由系统自动生成，请妥善保管。", new Font(bfChinese, 8, Font.NORMAL));
            noteParagraph.setAlignment(Element.ALIGN_CENTER);
            noteParagraph.setSpacingBefore(20);
            document.add(noteParagraph);

            document.close();
        } catch (Exception e) {
            throw new RuntimeException("生成PDF文档失败", e);
        }
    }

    /**
     * 通过反射获取对象属性值
     */
    private static Object getFieldValue(Object obj, String fieldName) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        if (fieldName.equals("tm")) {
            Object date = field.get(obj);
            return (date == null ? null : DateUtil.format((Date) date, "yyyy-MM-dd HH:mm:ss"));
        }
        return field.get(obj);

    }

    /**
     * 页眉页脚处理类
     */
    static class HeaderFooter extends PdfPageEventHelper {
        private String title;

        public HeaderFooter(String title) {
            this.title = title;
        }
        public HeaderFooter() {
        }

        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            try {
                String fontPath = "fonts/simhei.ttf";
                BaseFont bfChinese = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font footerFont = new Font(bfChinese, 8, Font.NORMAL);

                // 添加页脚
                PdfContentByte cb = writer.getDirectContent();

                // 页码
                String pageText = "第 " + writer.getPageNumber() + " 页";
                float textBase = document.bottom() - 20;

                // 居中显示页码
                float textSize = footerFont.getBaseFont().getWidthPoint(pageText, footerFont.getSize());
                cb.beginText();
                cb.setFontAndSize(bfChinese, 8);
                cb.setTextMatrix((document.right() - document.left() - textSize) / 2 + document.leftMargin(), textBase);
                cb.showText(pageText);
                cb.endText();

                if (title != null) {
                    // 添加页眉 - 标题
                    cb.beginText();
                    cb.setFontAndSize(bfChinese, 8);
                    cb.setTextMatrix(document.leftMargin(), document.top() + 10);
                    cb.showText(title);
                    cb.endText();

                    // 添加页眉下划线
                    cb.setLineWidth(0.5f);
                    cb.moveTo(document.leftMargin(), document.top());
                    cb.lineTo(document.right(), document.top());
                    cb.stroke();
                }
                // 添加页脚上划线
                cb.setLineWidth(0.5f);
                cb.moveTo(document.leftMargin(), document.bottom() - 5);
                cb.lineTo(document.right(), document.bottom() - 5);
                cb.stroke();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}